package com.jzo2o.market.job;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.market.constants.RedisConstants;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.service.IActivityService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @description: 优惠券定时任务
 * @author: jzo2o
 **/
@Slf4j
@Component
public class CouponJob {

    @Resource
    private IActivityService activityService;
    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 优惠卷定时预热到redis
     */

    @XxlJob("CouponStatusJobY")
    public void CouponStatusJob() {
        log.info("开始执行优惠券定时预热任务");
        // 查询符合条件的 优惠券活动

        List<Activity> activityList = activityService.list(Wrappers.<Activity>lambdaQuery()
                .eq(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus())
                .or(Wrapper -> Wrapper.eq(Activity::getStatus, ActivityStatusEnum.NO_DISTRIBUTE.getStatus())
                        .lt(Activity::getDistributeStartTime, LocalDateTime.now().plusMonths(1)))
        );
        if (activityList.isEmpty()){
            log.info("没有需要预热的优惠券");
        }

        try {
            redisTemplate.opsForValue().set(RedisConstants.RedisKey.ACTIVITY_CACHE_LIST, JSONUtil.toJsonStr(activityList));
            log.info("优惠券定时预热任务成功");
        } catch (Exception e) {
            log.error("优惠券定时预热任务失败"+e);
            throw new RuntimeException(e);
        }

    }
}
